import { ref, computed, onMounted, onUnmounted } from 'vue'

interface PerformanceMetric {
  name: string
  startTime: number
  endTime?: number
  duration?: number
  metadata?: Record<string, any>
}

interface MemoryInfo {
  usedJSHeapSize: number
  totalJSHeapSize: number
  jsHeapSizeLimit: number
}

export function usePerformance() {
  const metrics = ref<PerformanceMetric[]>([])
  const isMonitoring = ref(false)
  const memoryInfo = ref<MemoryInfo | null>(null)
  
  // 开始性能测量
  const startMeasure = (name: string, metadata?: Record<string, any>): string => {
    const metric: PerformanceMetric = {
      name,
      startTime: performance.now(),
      metadata
    }
    
    metrics.value.push(metric)
    
    // 使用Performance API标记
    if (performance.mark) {
      performance.mark(`${name}-start`)
    }
    
    return name
  }
  
  // 结束性能测量
  const endMeasure = (name: string): number => {
    const metric = metrics.value.find(m => m.name === name && !m.endTime)
    
    if (metric) {
      metric.endTime = performance.now()
      metric.duration = metric.endTime - metric.startTime
      
      // 使用Performance API测量
      if (performance.mark && performance.measure) {
        performance.mark(`${name}-end`)
        performance.measure(name, `${name}-start`, `${name}-end`)
      }
      
      return metric.duration
    }
    
    return 0
  }
  
  // 测量函数执行时间
  const measureFunction = async <T>(
    name: string,
    fn: () => Promise<T> | T,
    metadata?: Record<string, any>
  ): Promise<T> => {
    startMeasure(name, metadata)
    
    try {
      const result = await fn()
      return result
    } finally {
      endMeasure(name)
    }
  }
  
  // 获取内存使用情况
  const updateMemoryInfo = () => {
    if ('memory' in performance) {
      const memory = (performance as any).memory
      memoryInfo.value = {
        usedJSHeapSize: memory.usedJSHeapSize,
        totalJSHeapSize: memory.totalJSHeapSize,
        jsHeapSizeLimit: memory.jsHeapSizeLimit
      }
    }
  }
  
  // 格式化内存大小
  const formatMemorySize = (bytes: number): string => {
    const units = ['B', 'KB', 'MB', 'GB']
    let unitIndex = 0
    let size = bytes
    
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024
      unitIndex++
    }
    
    return `${size.toFixed(2)} ${units[unitIndex]}`
  }
  
  // 获取性能统计
  const getStats = computed(() => {
    const completedMetrics = metrics.value.filter(m => m.duration !== undefined)
    
    if (completedMetrics.length === 0) {
      return null
    }
    
    const durations = completedMetrics.map(m => m.duration!)
    const total = durations.reduce((sum, duration) => sum + duration, 0)
    const average = total / durations.length
    const min = Math.min(...durations)
    const max = Math.max(...durations)
    
    return {
      count: completedMetrics.length,
      total: Math.round(total * 100) / 100,
      average: Math.round(average * 100) / 100,
      min: Math.round(min * 100) / 100,
      max: Math.round(max * 100) / 100
    }
  })
  
  // 获取最近的测量结果
  const getRecentMetrics = (count: number = 10) => {
    return metrics.value
      .filter(m => m.duration !== undefined)
      .slice(-count)
      .map(m => ({
        name: m.name,
        duration: Math.round(m.duration! * 100) / 100,
        metadata: m.metadata
      }))
  }
  
  // 清除所有测量结果
  const clearMetrics = () => {
    metrics.value = []
    
    // 清除Performance API的测量结果
    if (performance.clearMeasures) {
      performance.clearMeasures()
    }
    if (performance.clearMarks) {
      performance.clearMarks()
    }
  }
  
  // 开始监控
  const startMonitoring = () => {
    isMonitoring.value = true
    updateMemoryInfo()
  }
  
  // 停止监控
  const stopMonitoring = () => {
    isMonitoring.value = false
  }
  
  // 获取页面加载性能
  const getPageLoadMetrics = () => {
    if (!performance.timing) {
      return null
    }
    
    const timing = performance.timing
    const navigation = performance.navigation
    
    return {
      // DNS查询时间
      dnsLookup: timing.domainLookupEnd - timing.domainLookupStart,
      // TCP连接时间
      tcpConnect: timing.connectEnd - timing.connectStart,
      // 请求响应时间
      request: timing.responseEnd - timing.requestStart,
      // DOM解析时间
      domParse: timing.domContentLoadedEventEnd - timing.domLoading,
      // 页面加载完成时间
      pageLoad: timing.loadEventEnd - timing.navigationStart,
      // 导航类型
      navigationType: navigation.type,
      // 重定向次数
      redirectCount: navigation.redirectCount
    }
  }
  
  // 监控长任务
  const observeLongTasks = () => {
    if ('PerformanceObserver' in window) {
      try {
        const observer = new PerformanceObserver((list) => {
          const entries = list.getEntries()
          entries.forEach((entry) => {
            if (entry.duration > 50) { // 长任务阈值50ms
              console.warn(`长任务检测: ${entry.name} 耗时 ${entry.duration.toFixed(2)}ms`)
            }
          })
        })
        
        observer.observe({ entryTypes: ['longtask'] })
        
        return () => observer.disconnect()
      } catch (error) {
        console.warn('无法监控长任务:', error)
      }
    }
    
    return () => {}
  }
  
  let longTaskObserver: (() => void) | null = null
  
  onMounted(() => {
    updateMemoryInfo()
    longTaskObserver = observeLongTasks()
  })
  
  onUnmounted(() => {
    if (longTaskObserver) {
      longTaskObserver()
    }
  })
  
  return {
    metrics: computed(() => metrics.value),
    memoryInfo: computed(() => memoryInfo.value),
    isMonitoring: computed(() => isMonitoring.value),
    stats: getStats,
    startMeasure,
    endMeasure,
    measureFunction,
    updateMemoryInfo,
    formatMemorySize,
    getRecentMetrics,
    clearMetrics,
    startMonitoring,
    stopMonitoring,
    getPageLoadMetrics
  }
}